<template>
    <div>
        <el-select :size="size" :collapse-tags="collapseTags" style="width:100%;" 
            v-model="selectArray" multiple placeholder="请选择">
            <el-option v-for="item in currentOptions" :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
        </el-select>
    </div>
</template>

<script>
module.exports = {
    data: function() {
        return {
            selectArray: [],
            currentOptions: []
        }
    },
    props: {
        size: {
            default: 'mini',
            type: String
        },
        value: String,
        options: Array,
        map: Object,
        collapseTags: {
            default:true,
            type: Boolean
        }
    },
    created: function() {
        if(this.options != null) {
            this.currentOptions = this.options;
        } else if(this.map != null){
            this.currentOptions = this.fromMap();
        } else {
            console.error("异常，缺少 options 或 map");
        }
        console.log('currentOptions', this.currentOptions);
        this.loadValue();
    },
    methods: {
        fromMap: function() {
            var arr = [];
            for(var key in this.map) {
                var value = this.map[key];
                arr.push({
                    value: key,
                    label: value
                });
            }
            return arr;
        },
        loadValue: function() {
            if(this.value != null && this.value != '') {
                var arr = this.value.split(',');
                if(!Util.isArrayEqual(arr, this.selectArray) ) {
                    this.selectArray = arr;
                }
            } else {
                // 传入为空则清空数据
                this.selectArray = [];
            }
        }
    },
    watch: {
        // 双向绑定，数据流入，显示
        value: function(v) {
            this.loadValue();
        },
        selectArray: function(array) {
            // console.log('change', array);
            var arr = array.join(',');
            this.$emit('input', arr);
        },
        map: function() {
            this.currentOptions = this.fromMap();
        }
    },
}
</script>